<template>
    <div>
        <el-upload :action="actionUrl" v-model:file-list="imageUrlList" list-type="picture-card" :headers="headers"
            :data="payload" :limit="limit" :disabled="disabled" :on-success="handleSuccess"
            :before-upload="handleBeforeUpload" :on-preview="handlePreview" :on-error="handleError"
            :on-remove="handleRemove">
            <el-icon>
                <ele-Plus />
            </el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
            <img w-full :src="preViewUrl" alt="图片预览" />
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, defineComponent, ref } from 'vue';
import type { UploadFile, UploadFiles, UploadRawFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus';
import useFileInfo from '/@/api/jdfsystem/file-info';
import { useEmployeeStore } from '/@/stores/employee-info';
import useObjectUtil from '/@/utils/objectUtil';
import MESSAGE from '/@/enums/message-enum';

interface State {
    actionUrl: string,
    headers: any,
    multiple: boolean | false,
    name: string,
    payload: any,
    accept: string,
    limit: number | 1,
    dialogVisible: boolean | false,
    imageUrlList: { name: string, url: string }[] | [],
    preViewUrl: string | undefined,
    disabledVlaue: boolean | false,
}

export default defineComponent({
    name: 'avatar',
    props: {
        imageIdList: {
            type: Array<string>,
            default: [],
        },
        multiple: {
            type: Boolean,
            default: false,
        },
        name: {
            type: String,
            default: 'file',
        },
        accept: {
            type: String,
            defalut: 'image/png,image/jpeg,image/jpg',
        },
        limit: {
            type: Number,
            default: 1,
        },
        payload: {
            type: Object,
            default: undefined
        },
        disabled: {
            type: Boolean,
            default: true
        }
    },
    setup(props, context) {
        const fileStore = useFileInfo();
        const employeeStore = useEmployeeStore();
        const { multiple, name, accept, limit, imageIdList, payload, disabled } = { ...props };
        const imageInfoList: { name: string, url: string }[] = [];
        imageIdList.filter(f => useObjectUtil.isNotNull(f)).forEach(f => imageInfoList.push({ name: f, url: fileStore.view(f) }));
        const state = reactive<State>({
            actionUrl: fileStore.uploadUrl(),
            headers: {
                'Authorization': employeeStore.getToken(),
            },
            multiple: multiple,
            name: name,
            accept: accept || 'image/png,image/jpeg,image/jpg',
            limit: limit,
            imageUrlList: imageInfoList,
            payload: payload,
            dialogVisible: false,
            preViewUrl: undefined,
            disabledVlaue: disabled,
        });
        const methodMap = reactive({
            handleSuccess: function (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) {
                const res: any = uploadFile.response;
                if (MESSAGE.OK !== res.code) {
                    context.emit('onSuccess', []);
                    ElMessage.error('图片上传失败：' + res.msg);
                    return;
                }
                const fileIdList: string[] = uploadFiles.filter(f => f.status === 'success').map(m => {
                    const response: any = m.response;
                    return response.data;
                });
                context.emit('onSuccess', fileIdList);
            },
            handleRemove: function (uploadFile: UploadFile, uploadFiles: UploadFiles) {
                const fileIdList: string[] = uploadFiles.filter(f => f.status === 'success').map(m => {
                    const response: any = m.response;
                    return response.data;
                });
                context.emit('onSuccess', fileIdList);
            },
            handleError: function (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) {
                console.info(uploadFile);
                ElMessage.error('图片上传失败：' + error.message);
            },
            handleBeforeUpload: function (rawFile: UploadRawFile) {
                const imageTypeList: string[] = state.accept.split(',');
                if (!imageTypeList.includes(rawFile.type)) {
                    console.info("支持格式:" + state.accept);
                    ElMessage.error('图片必须是' + state.accept + '格式！');
                    return false;
                }
                if (rawFile.size / 1024 / 1024 > 2) {
                    ElMessage.error('图片大小不能超过：2MB!')
                    return false
                }
                return true;
            },
            handlePreview: function (uploadFile: UploadFile) {
                state.preViewUrl = uploadFile.url;
                state.dialogVisible = true;
            },
        });
        const formRef = ref<FormInstance>();
        return {
            formRef,
            ...toRefs(state),
            ...toRefs(methodMap),
        };
    },
});
</script>
<style scoped lang="scss">
@import '/@/views/file-info/file-info.scss';
</style>
